using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;

namespace Kenly.DBFramework.ORMCodeHelper
{
    public static class ConfigSerializer
    {
       
        public static void Serialize(string filePath,object obj)
        {
            if (obj == null)
            {
                return;
            }

            try
            {
                System.Xml.Serialization.XmlSerializerFactory xmlSerializerFactory = new System.Xml.Serialization.XmlSerializerFactory();
                System.Xml.Serialization.XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(obj.GetType(), obj.GetType().Name);
                System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
                xmlSerializer.Serialize(stream, obj);
                stream.Close();
            }
            catch
            {
            }
        }

        public static object Deserialize(string filePath,Type targetType)
        {
            if (!System.IO.File.Exists(filePath) || targetType==null)
            {
                return null;
            }

            object obj = null;
            try
            {
                System.Xml.Serialization.XmlSerializerFactory xmlSerializerFactory = new System.Xml.Serialization.XmlSerializerFactory();
                System.Xml.Serialization.XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(targetType, targetType.Name);
                System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
                obj = xmlSerializer.Deserialize(stream);
                stream.Close();
            }
            catch
            {
            }
            return obj;

        }
    }
}
